import { Component } from "react";
import {
  Table,
  Input,
  // Select,
  Button,
  Modal,
  message,
  Space,
  Tabs,
} from "antd";
import IconFont from "../../../../assets/ICON";
// import { Language } from "../../../../i18n/Language";
// import { PlusOutlined } from "@ant-design/icons";
import React from "react";
import moment from "moment";

import Consequence from "../ResultsQuery/compontents/Consequence";
import {
  terminalStatusList,
  agreementList,
  getterminaltime,
  getupdown,
  gettimeseconds,
} from "../deviceseversapi";
import "./index.less";

export interface ScreenProps {}
// const { Option } = Select;
const { TabPane } = Tabs;
export interface ScreenState {
  type: Number;
  time: "date" | "time" | "month" | "year" | "week" | "quarter";
  loading: boolean;
  selectedRowKeys: number[];
  visible: boolean;
  binding: boolean;
  terminalselectedRowKeys: number[];
  datalist: number[];
  status: number;
  id: string;
  conditionaddress: string;
  conditionname: string;
  conditionno: string;
  addtitle: string;
  batch: string;
  condition: string;
  // id:number[];
  terminaldatalist: number[];
  terminaltotal: number;
  terminalpage: number;
  terminalsize: number;
  terminalname: string;
  terminalid: string;
  addedit: number;
  protocollist: number[];
  page: number;
  size: number;
  total: number;
  // isModalVisible:Boolean;
  // setIsModalVisible:Boolean;
}
export enum dateEnum {
  "date" = "date",
  "time" = "time",
  "month" = "month",
  "year" = "year",
}

class TerminalDebugging extends Component<ScreenProps, ScreenState> {
  state = {
    type: 1,
    time: dateEnum.date,
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
    isModalVisible: false,
    visible: false,
    binding: false,
    addtitle: "上下线记录",
    batch: "删除终端设备信息",
    terminallist: {},
    id: "",
    datalist: [],
    terminaldatalist: [],
    status: 1, //1就是删除 2是解绑 3是绑定
    conditionno: "",
    conditionname: "",
    conditionaddress: "",
    terminalselectedRowKeys: [],
    terminalid: "",
    condition: "", //新增协议默认内容  编辑协议文本
    terminaltotal: 0,
    terminalpage: 1,
    terminalsize: 5,
    terminalname: "",
    protocollist: [],
    page: 1,
    size: 10,
    total: 0,

    // id:0,
    addedit: 1, //1新增或者2编辑
  };
  private terminalcolumns = [
    {
      key: "name",
      title: "终端名称",
      dataIndex: "name",
      width: 200,
    },
    {
      key: "status",
      title: "状态",
      dataIndex: "status",
      width: 80,
      render: (text, record, index) => {
        let isLoad = "";
        if (record.status === "1") {
          isLoad = '<div class="offline1">登录</div>';
        } else {
          isLoad = '<div class="offline">登出</div>';
        }
        return <div dangerouslySetInnerHTML={{ __html: isLoad }} />;
      },
    },
    {
      key: "changeTime",
      title: "发生时间",
      dataIndex: "changeTime",
      width: 150,
      render: (text, record) => {
        let newDate = moment(record.changeTime, "x").format("YYYY-MM-DD HH:mm"); //parse string
        return <span>{newDate}</span>;
      },
    },
  ];
  private columns = [
    {
      key: "no",
      title: "终端编号",
      dataIndex: "no",
      width: 100,
    },
    {
      key: "name",
      title: "终端名称",
      dataIndex: "name",
      width: 200,
    },
    {
      key: "typeName",
      title: "协议名称",
      dataIndex: "typeName",
      width: 100,
    },
    {
      key: "address",
      title: "通讯地址",
      dataIndex: "address",
      width: 100,
    },
    {
      key: "installAdd",
      title: "状态",
      dataIndex: "installAdd",
      width: 100,
      // status
      render: (text, record) => {
        let isLoad = "";
        if (record.status === "1") {
          isLoad =
            '<div class="network"><span class="on_line"></span><span>在线</span></div>';
        } else {
          isLoad =
            '<div class="network"><span class="off_line"></span> <span>离线</span></div>';
        }
        return <div dangerouslySetInnerHTML={{ __html: isLoad }} />;
      },
    },

    {
      title: "上下线记录",
      key: "address",
      width: 100,
      render: (text, record) => (
        <Space size="middle">
          <span
            style={{ cursor: "pointer" }}
            onClick={(event) => {
              var that = this;
              this.setState(
                {
                  visible: true,
                  addtitle: "上下线记录",
                  terminalid: record.id,
                },
                () => {
                  that.terminalfetchget();
                }
              );
            }}
          >
            <IconFont type="icon_shangxiaxian" style={{ color: "#1890FF" }} />
          </span>
        </Space>
      ),
    },
  ];
  componentDidMount() {
    this.fetchget();
    this.agreement();
  }

  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };

  render() {
    //时钟读取
    const timeseconds = () => {
      if (this.state.selectedRowKeys.length === 0) {
        message.info("请选择终端");
        return;
      }
      // let that = this;
      let data = {
        terminalId: this.state.selectedRowKeys[0],
      };
      gettimeseconds(data)
        .then((res: any) => {
          if (res) {
            if (res.code === 200) {
              message.info("时钟读取命令已下发，请查看执行结果!");
            } else {
              message.error(res.message);
            }
          } else {
            message.error("失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    //时钟对时
    const Terminaltime = () => {
      if (this.state.selectedRowKeys.length === 0) {
        message.info("请选择终端");
        return;
      }
      // let that = this;
      let data = {
        terminalId: this.state.selectedRowKeys[0],
      };
      getterminaltime(data)
        .then((res: any) => {
          if (res) {
            if (res.code === 200) {
              message.info("时钟对时命令已下发，请查看执行结果!");
            } else {
              message.error(res.message);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };

    let paginationterminal = {
      total: this.state.terminaltotal,
      defaultCurrent: this.state.terminalpage,
      pageSize: this.state.terminalsize,
      showSizeChanger: true,
      onShowSizeChange: (current, pageSize) => {},
      onChange: (current, pageSize) => {
        that.setState(
          {
            terminalpage: current,
          },
          () => {
            this.terminalfetchget();
          }
        );
      },
    };
    const handleOk = () => {
      this.setState({
        visible: false,
      });
    };
    //获取协议类型下拉

    const handleCancel = () => {
      this.setState({
        visible: false,
      });
    };

    //表格复选框
    let that = this;
    let pagination = {
      total: this.state.total,
      defaultCurrent: this.state.page,
      pageSize: this.state.size,
      showSizeChanger: true,
      onShowSizeChange: (current, pageSize) => {},
      onChange: (current, pageSize) => {
        that.setState(
          {
            page: current,
          },
          () => {
            this.fetchget();
          }
        );
      },
    };

    return (
      <>
        <div className="TerminalDebugging">
          <Tabs defaultActiveKey="1">
            <TabPane tab="终端调试" key="1">
              <div className="rowcon_body">
                <div className="querystat">
                  终端编号：
                  <Input
                    className="input"
                    placeholder="请输入终端编号"
                    value={this.state.conditionno}
                    onChange={(event) => {
                      this.numberchange(event);
                    }}
                  />
                </div>
                <div className="query">
                  终端名称：
                  <Input
                    className="input"
                    placeholder="请输入终端名称"
                    value={this.state.conditionname}
                    onChange={(event) => {
                      this.namechange(event);
                    }}
                  />
                </div>
                <div className="query">
                  终端地址：
                  <Input
                    className="input"
                    placeholder="请输入终端地址"
                    value={this.state.conditionaddress}
                    onChange={(event) => {
                      this.addresschange(event);
                    }}
                  />
                </div>
                <div className="query">
                  <Button
                    type="primary"
                    onClick={() => {
                      this.fetchget();
                    }}
                  >
                    查询
                  </Button>
                </div>
              </div>
              <div className="subject">
                <div className="operation">
                  <Button
                    type="primary"
                    className="increased"
                    size="middle"
                    onClick={Terminaltime}
                  >
                    终端对时
                  </Button>

                  <Button
                    type="primary"
                    className="seconds"
                    size="middle"
                    onClick={timeseconds}
                  >
                    时钟读秒
                  </Button>
                </div>
                <div>
                  <Table
                    rowSelection={{
                      type: "radio",
                      onChange: (selectedRowKeys, selectedRows) => {
                        this.radioonChange(selectedRowKeys, selectedRows);
                      },
                    }}
                    style={{ paddingTop: 16 }}
                    columns={this.columns}
                    dataSource={this.state.datalist}
                    pagination={pagination}
                  />
                </div>
              </div>
              <div>
                {/* 终端上下线记录弹窗 */}
                <Modal
                  title={this.state.addtitle}
                  visible={this.state.visible}
                  onOk={handleOk}
                  onCancel={handleCancel}
                  width="682px"
                >
                  <div className="addtotality">
                    <Table
                      columns={this.terminalcolumns}
                      dataSource={this.state.terminaldatalist}
                      pagination={paginationterminal}
                    />
                  </div>
                </Modal>
              </div>
            </TabPane>
            <TabPane tab="结果查询" key="2">
              <Consequence />
            </TabPane>
          </Tabs>
        </div>
      </>
    );
  }
  async fetchget() {
    let data = {
      pageIndex: this.state.page,
      pageSize: this.state.size,
      queryData: {
        address: this.state.conditionaddress,
        name: this.state.conditionname,
        no: this.state.conditionno,
      },
    };
    let res: any = await terminalStatusList(data).catch((err) => {
      console.log(err);
    });
    const json: any = res;
    let date = json.data.records;
    for (let i in date) {
      let key = "key";
      let value = date[i].id;
      date[i][key] = value;
    }

    if (json.success) {
      this.setState({
        datalist: date,
        total: json.data.total,
      });
    }
  }
  namechange(e) {
    this.setState({
      conditionname: e.target.value,
    });
  }
  addresschange(e) {
    this.setState({
      conditionaddress: e.target.value,
    });
  }
  //单选事件
  radioonChange(selectedRowKeys: any, selectedRows: any) {
    this.setState({ selectedRowKeys });
  }
  numberchange(e) {
    this.setState({
      conditionno: e.target.value,
    });
  }

  //获取协议类型下拉
  async agreement() {
    let res: any = await agreementList().catch((err) => {
      console.log(err);
    });
    const json: any = res;
    if (res) {
      this.setState({
        protocollist: json.data,
      });
    }
  }
  //获取弹窗终端列表
  //terminaldatalist
  async terminalfetchget() {
    let data = {
      pageIndex: this.state.terminalpage,
      pageSize: this.state.terminalsize,
      queryData: this.state.terminalid,
    };
    let res: any = await getupdown(data).catch((err) => {
      console.log(err);
    });
    const json: any = res;
    if (json.success) {
      let date = json.data.records;

      this.setState({
        terminaldatalist: date,
        terminaltotal: json.data.total,
      });
    }
  }

  getDate(date: any, dateString: String) {}
}

export default TerminalDebugging;
